import HeaderView from '@/components/Header/index'
import LoadingView from '@/components/Loading/index'
import { GetDetail, IsCollect, AddCart } from '@/api/detail'
import { useEffect, useState } from 'react'
import style from './index.module.scss'
import { Image, Button, Tag, Tabs, Toast } from 'antd-mobile'
import { HeartOutline } from 'antd-mobile-icons'
import { itemTtype } from './type'
import { useActivate } from 'react-activation'
import { useNavigate } from 'react-router-dom'
import { cartNumAsync } from '@/reduxToolkit/reducers/cartNum'
import { useDispatch, useSelector } from 'react-redux'

const Detail = () => {
  const [flag, setFlag] = useState(true)
  const [loadingCode, setLoadingCode] = useState(1)
  const [collectFlag, setCollectFlag] = useState(0) // 是否收藏产品
  const [tuijian, setTuijian] = useState([]) // 图书推荐
  const [id, setID] = useState(0) // 记录是否 点击的同一个产品的ID
  const [activeKey, setActiveKey] = useState('desc') // tab选项卡当前项
  const ID = useSelector((state: {detail: {value: number}}) => state.detail.value) // redux 跳转路由保存的ID
  const fromPath = useSelector((state: {detail: {fromPath: string}}) => state.detail.fromPath) // redux 跳转路由保存的上一级路由地址
 
  // 产品信息
  const [product, setProduct] = useState({
    id: 0,
    cover_url: '',
    title: '',
    price: 0,
    collects_count: 0,
    details: '',
    description: ''
  })

  const navigate = useNavigate()
  const dispatch: any = useDispatch()

  // 数据初始化
  const init = async () => {
    const res = await GetDetail(ID).catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
    })

    try {
      if(res?.status === 200) {
        setFlag(false)
        setID(ID)
        setProduct(res.data.goods)
        setTuijian(res.data.like_goods)
        setCollectFlag(res.data.goods.is_collect)
      }  
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    init()
  }, [ID])

  // 缓存页面激活
  useActivate(() => {
    if(ID === id) {
      setFlag(false)
    } else {
      setFlag(true)
      setActiveKey('desc')
    }
  })

  // 立即购买 或者 加入购物车
  const addBuy = async (type: string) => {
    const res = await AddCart({goods_id: product.id, num: 1}).catch((err) => {
      if(err.status === 401) {
        Toast.show({ icon: 'success', content: '请先登录呀', duration: 1500, maskClickable: false, afterClose: () => {
          navigate('/login', {state: {pathname: '/detail', id: product.id}}) 
        }})
      }
    })
    
    try {
      if(res?.status === 201 || res?.status === 204) {
        dispatch(cartNumAsync())
        if(type === 'add') {
          Toast.show({ icon: 'success', content: '添加成功', duration: 1500, maskClickable: true})
        } else {
          Toast.show({ icon: 'loading', content: '跳转中', duration: 1500, maskClickable: true, afterClose: () => {
            navigate('/shopcart')
          }})
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 收藏产品
  const isCollectProduct = async () => {
    const res = await IsCollect(product.id).catch((err) => {
      if(err.status === 401) {
        Toast.show({ icon: 'success', content: '请先登录呀', duration: 1500, maskClickable: false, afterClose: () => {
          navigate('/login', {state: {pathname: '/detail', id: product.id}}) 
        }})
      }
    })

    try {
      if(res?.status === 201) {
        setCollectFlag(1)
        Toast.show({ icon: 'success', content: '收藏成功', duration: 1500, maskClickable: false })
      }
      if(res?.status === 204) {
        setCollectFlag(0)
        Toast.show({ icon: 'success', content: '取消收藏', duration: 1500, maskClickable: false })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 推荐产品
  const getTuijian = () => {
    return tuijian.map((item: itemTtype) => {
      return (
        <div className={style.item} key={item.id}>
           <Image src={item.cover_url}/>
           <p className={style.title}>{item.title}</p>
           <p className={style.description}>
            <span className="price">￥{item.price}</span> 
            <HeartOutline className={style.like} />
            <span>{item.collects_count}</span>
            </p>
        </div>
      )
    })
  }

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title='商品详情' backIcon={true} backPath={fromPath}></HeaderView>

      <div className={style.content}>
        {/* 产品图 */}
        <Image src={product.cover_url}/>

        {/* 产品信息 */}
        <div className={style.desc}>
          <p className={style.title}>{product.title}</p>
          <p className={style.ms}>{product.description}</p>

          <div className={style.tag}>
            <Tag color='#ff6430' fill='outline'>推荐</Tag>
            <Tag color='#ff6430' fill='outline'>新书</Tag>
          </div>

          <p className={style.price}>
            <span>￥</span>
            <span className={style.jg}>{product.price}</span>
            <span>.00</span>
          </p>

          <div className={style.btn}>
            <Button size='mini' color='warning' onClick={() => addBuy('add')}>加入购物车</Button>
            <Button size='mini' color='danger' onClick={() => addBuy('buy')}>立即购买</Button>
            <Button size='mini' color={collectFlag ? 'primary' : 'default'} onClick={() => isCollectProduct()}>
              {collectFlag ? '已收藏' : '未收藏'}
            </Button>
           </div>
        </div>

        {/* 选项卡信息 */}
        <Tabs activeKey={activeKey} onChange={(val: string) => setActiveKey(val)}>
          <Tabs.Tab title='概述' key='desc'>
            <div className={style.img} dangerouslySetInnerHTML = {{ __html : product.details }}></div>
          </Tabs.Tab>
          <Tabs.Tab title='热评' key='rating'>
            <p className={style.no}>暂无评价</p>
          </Tabs.Tab>
          <Tabs.Tab title='相关图书' key='about'>
            {getTuijian()}
          </Tabs.Tab>
        </Tabs>
      </div>

      {/* 加载中或者加载超时 */}
      {flag && <LoadingView loadingCode={loadingCode}></LoadingView>}
    </>
  )
}
export default Detail